<template>
  <div class="loginBox">
    <el-row>
      <el-col :lg="24">
        <img src="@/assets/logo.png" style="width: 34px; margin-left: 15%;margin-top: 8px; float: left;">
        <div class="header">
          <span style="height: 50px; line-height: 50px; margin-left: 10px"><strong style="font-size: 20px">{{ env.VITE_APP_TITLE }}</strong></span>
        </div>
      </el-col>
    </el-row>
    <el-row style="min-height: calc(100vh - 100px);" align="middle" justify="center">
      <el-col :md="10" :span="0" style="justify-content: right" class="box-align-center">
        <div class="leftBox animate__animated animate__slideInLeft" ></div>
      </el-col>
      <el-col :md="14" :span="24" class="box-align-center" style="padding: 5%">
        <div class="rightBox animate__animated animate__slideInLeft">
          <el-form :model="loginForm" :rules="rules" ref="ruleFormRef" style="overflow:hidden;" @submit.native.prevent  >
            <el-form-item>
              <img src="@/assets/logo.png" style="width: 50px">
              <span style="margin-left: 20px; font-size: 24px;"><strong>登录</strong></span>
            </el-form-item>
            <el-radio-group v-model="isCollapse"
                            style="margin-bottom: 20px;margin-top: 10px">
              <el-radio-button :label="true" class="radio-button">账号登录</el-radio-button>
              <el-radio-button :label="false" class="radio-button">邮箱登录</el-radio-button>
            </el-radio-group>

            <div v-if="isCollapse" class="animate__animated animate__slideInLeft animate__faster">
              <el-form-item label="账 号" class="marbot5"></el-form-item>
              <el-form-item prop="username" class="marbot10">
                <el-input v-model="loginForm.username" placeholder="请输入您的用户名" @keyup.enter="handleLogin(ruleFormRef)" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="密 码" class="marbot5"></el-form-item>
              <el-form-item prop="password" class="marbot10">
                <el-input v-model="loginForm.password" show-password autocomplete="new-password"
                          placeholder="请输入您的密码" @keyup.enter="handleLogin(ruleFormRef)" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="验证码" class="marbot5"></el-form-item>
              <el-form-item prop="code">
                <el-input v-model="loginForm.code" placeholder="请输入验证码" @keyup.enter="handleLogin(ruleFormRef)" style="width: 55%; height: 36px"></el-input>
                <img :src="codeUrl" @click="getCode" style="height: 36px; border: #27ae60 1px solid;border-radius: 4px;margin-left: 20px">
              </el-form-item>
              <el-form-item>
                <el-button class="login-button" type="primary" @click="handleLogin(ruleFormRef)">登 录</el-button>
              </el-form-item>
            </div>

            <div v-else class="animate__animated animate__slideInRight animate__faster">
              <el-form-item label="邮 箱" class="marbot5"></el-form-item>
              <el-form-item prop="email" class="marbot10">
                <el-input v-model="loginForm.email" placeholder="请输入您的邮箱" @keyup.enter="handleLogin(ruleFormRef)" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="密 码" class="marbot5"></el-form-item>
              <el-form-item prop="password" class="marbot10">
                <el-input v-model="loginForm.password" show-password autocomplete="new-password"
                          placeholder="请输入您的密码" @keyup.enter="handleLogin(ruleFormRef)" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="验证码" class="marbot5"></el-form-item>
              <el-form-item prop="code">
                <el-input v-model="loginForm.code" placeholder="请输入验证码" @keyup.enter="handleLogin(ruleFormRef)" style="width: 55%; height: 36px"></el-input>
                <img :src="codeUrl" @click="getCode" style="height: 36px; border: #27ae60 1px solid;border-radius: 4px;margin-left: 20px">
              </el-form-item>
              <el-form-item>
                <el-button class="login-button" type="primary" @click="handleLogin(ruleFormRef)" >登 录</el-button>
              </el-form-item>
            </div>

            <el-form-item style="display: flex; justify-content: flex-end">
              <div class="reset-text" @click="router.push({path:'/reset'})">忘记密码</div>
              <div class="register-text" @click="router.push({path:'/register'})">还没有账号？立即注册</div>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :lg="24">
        <div class="footer">
          <span style="height: 50px; line-height: 50px; margin-left: 10px; color: #555555">
            Powered By
            <a href="https://gitee.com/smmiaoya" target="_blank">喵喵</a>
          </span>
        </div>
      </el-col>
    </el-row>
  </div>

</template>

<script setup>

import {reactive, ref, onMounted} from "vue";
import {getUserInfo} from "@/api/userInfo.js";
import {login, getCodeImg, checkToken, getRouters} from "../../../api/login.js";
import {ElMessage} from "element-plus";
import router from "../../../routers/index.js";
import {storeToRefs} from "pinia";
import {useRouterStore} from "@/store/router.js";
import {getInfo} from "@/api/app.js";
const isCollapse = ref(true)
const ruleFormRef = ref()
const codeUrl = ref('')
const loginForm = reactive({
  username: null,
  email: null,
  password: null,
  code: null,
  uuid: null,
})
const rules = reactive({
  username: [
    // required是否必填,message不符合此规则时的提示信息,
    // trigger触发此条规则校验的时机，有两个值, blur 或 change,默认就是blur和change都会进行校验
    // min此字段的最小长度，max此字段的最大长度
    // pattern 正则表达式
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9]{4,20}$/, message: '用户名长度为4 - 20位,只能由数字或字母构成'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
    {pattern: /^[0-9A-Za-z]{4}$/, message: '请输入正确格式的验证码'}
  ]
})
const store = useRouterStore()
const {addDynamicRoutes} = store
const env = import.meta.env

onMounted(() => {
  checkLogin()
})
function checkLogin(){
  if(window.localStorage.getItem("token") != null){
      checkToken().then(res => {
        if(res.code == 200){
          router.push("/index")
        }else{
          getCode()
        }
      })
  }else{
    getCode()
  }
}

function getCode(){
  getCodeImg().then(res => {
    codeUrl.value = "data:image/gif;base64," + res.data.img
    loginForm.uuid = res.data.uuid
  })
}

function handleLogin(formEl){
  if (!formEl) return
  formEl.validate((valid) =>{
    if(valid){
      return new Promise((resolve, reject) => {
        login(loginForm.username,loginForm.password,loginForm.code,loginForm.uuid).then(async res => {
          if (res.code == 200) {
            window.localStorage.setItem("token", res.data.token)
            await getUserInfo().then(res => {
              window.localStorage.setItem("miaomiao-userInfo", JSON.stringify(res.data))
            })
            addDynamicRoutes().then(() => {
              router.push({path: "/index"})
              ElMessage.success(res.msg)
            })
          } else {
            window.localStorage.removeItem("token")
            window.localStorage.removeItem("miaomiao-userInfo")
            getCode()
            ElMessage.error(res.msg)
          }
        }).catch(error => {
          getCode()
          reject(error)
        })
      })
    }else{
      ElMessage.error("请正确填写登录信息")
    }
  })

}

</script>

<style lang="scss" scoped>
.loginBox {
  width: 100vw;
  min-height: 100vh;
  background: url(@/assets/bg.jpg);
  background-size: cover;
  .box-align-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .header {
    height: 50px;
    line-height: 50px;
    background-color: white;
  }
  .footer{
    height: 50px;
    line-height: 50px;
    background-color: white;
    display: flex;
    justify-content: center;
    a{
      color: #27ae60;
      text-decoration: none;
    }
  }

  .leftBox {
    width: 600px;
    height: 600px;
    //margin-right: 200px;
    background: url(@/assets/bg1.png);
    background-size: cover;
  }

  .rightBox {
    width: 500px;
    //height: 550px;
    padding: 40px;
    padding-bottom: 0px;
    background-color: white;
    border-radius: 20px;
    box-shadow: 0 4px 16px 0 rgba(33, 37, 46, .12);

    .label-text {
      color: #606266;
      font-size: 16px
    }
    .login-button {
      width: 100%;
      margin-top: 10px;
      height: 35px;
    }
    .register-text{
      margin-top: 10px;
      color: gray;
      cursor: pointer;
    }
    .register-text:hover{
      color: #00b259;
    }
    .reset-text{
      margin-top: 10px;
      color: gray;
      cursor: pointer;
      flex: 1;
    }
    .reset-text:hover{
      color: #00b259;
    }
  }

}
.marbot5{
  margin-bottom: 5px;
}
.marbot10{
  margin-bottom: 10px;
}
.marbot20{
  margin-bottom: 20px;
}

</style>
